﻿using Digitalmes.ControlEx;

namespace Digitalmes.Gallery.ViewModels.Pages;

public partial class RectCtlViewModel : ObservableObject
{
    record class RectProfileModel(string ProfileName, string FileName, RectProfile RectProfile);

    private readonly string _profileDirPath = Path.Combine(AppContext.BaseDirectory, "Assets", "RectProfiles");
    private readonly Dictionary<string, RectProfileModel> _profileMap = [];

    public RectCtlViewModel()
    {
        InitializeViewModel();
    }

    /// <summary>
    /// Rect 画布
    /// </summary>
    [ObservableProperty]
    private RectCanvas _rectCanvas = new();

    /// <summary>
    /// 当前 Rect 配方名称
    /// </summary>
    [ObservableProperty]
    private string? _currentProfileName;

    /// <summary>
    /// 是否启用点位编辑
    /// </summary>
    [ObservableProperty]
    private bool _enableEdit;

    /// <summary>
    /// 配方集合
    /// </summary>
    [ObservableProperty]
    private List<string>? _profileCollection;

    /// <summary>
    /// 绑定选中的下拉配置值
    /// </summary>
    [ObservableProperty]
    private string? _selectedProfileValue;

    /// <summary>
    /// 启动/关闭点位编辑
    /// </summary>
    /// <param name="isChecked"></param>
    [RelayCommand]
    private void OnEnableEdit(bool isChecked)
    {
        EnableEdit = isChecked;
        RectCanvas.AllowMouseDrop = EnableEdit;
        ProfileCollection = ["", .. _profileMap.Keys];

        SelectedProfileValue = EnableEdit ? CurrentProfileName : "";
    }

    /// <summary>
    /// 下拉配方更改事件
    /// </summary>
    [RelayCommand]
    private void OnSelectProfileChanged()
    {
        var profileName = SelectedProfileValue;
        if (!string.IsNullOrEmpty(profileName))
        {
            SetProfile(profileName);
        }
    }

    /// <summary>
    /// 保存配方
    /// </summary>
    [RelayCommand]
    private void OnSaveProfile()
    {
        var profileName = SelectedProfileValue;
        if (string.IsNullOrEmpty(profileName))
        {
            return;
        }

        var profile = _profileMap[profileName];
        var leds = RectCanvas.GetCollection();
        foreach (var point in profile.RectProfile.Points)
        {
            var led = leds.FirstOrDefault(s => s.No == point.No && s.Group == point.Group);
            if (led != null)
            {
                point.X = Math.Round(led.CanvasPosition.X, 1);
                point.Y = Math.Round(led.CanvasPosition.Y, 1);
            }
        }

        var content = profile.RectProfile.ToJson(true);
        File.WriteAllText(Path.Combine(_profileDirPath, profile.FileName), content);
    }

    private void InitializeViewModel()
    {
        LoadProfile();
        SetProfile();
    }

    private void LoadProfile()
    {
        // 从指定目录中找到配方文件
        if (!Directory.Exists(_profileDirPath))
        {
            return;
        }

        foreach (var path in Directory.GetFiles(_profileDirPath, "*.json", SearchOption.TopDirectoryOnly))
        {
            var content = File.ReadAllText(path);
            var ledProfile = content.FromJson<RectProfile>()!;
            _profileMap[ledProfile.Name] = new RectProfileModel(ledProfile.Name, Path.GetFileName(path), ledProfile);
        }
    }

    private void SetProfile(string? profileName = null)
    {
        var profile = profileName != null && _profileMap.TryGetValue(profileName, out var m)
            ? m
            : _profileMap.Values.FirstOrDefault(s => s.RectProfile.IsDefault) ?? _profileMap.Values.FirstOrDefault();
        if (profile != null)
        {
            CurrentProfileName = profile.ProfileName;
            RectCanvas.ChangeProfile(profile.RectProfile);
        }
    }
}
